class SitesController < ApplicationController
    include AuthenticatedSystemBrowse
  
    before_filter :login_required, :only => [ :edit, :update, :update_icon, :newpost, :set_neighbor, :votebad, :votegood ]
    #before_filter :admin_required, :only => [ :destroy ]
  
    def search
        if params[:q].nil? || params[:q].blank?
            redirect_back_or_default(:controller => 'browse', :action => 'index')
        else
            @sites = Site.paginate_search(params[:q], {:page => params[:page]})
            @page_title = '搜索场所 - ' + params[:q]
        end
    end
  
    def show
        @site = Site.find(params[:id], :include => [ :communities ])
        
        respond_to do |format|
            format.html do
                @posts = SitePost.paginate_by_site_id @site, :include => [ :site ], :page => params[:page], :order => 'replied_at desc'
                @tags = site_tags(@site.id)
                @page_title = @site.title
            end
            format.rss  do
                @posts = SitePost.find_all_by_site_id @site, :include => [ :site ], :order => 'replied_at desc', :limit => "25"
                render :action => "show.rxml", :layout => false
            end
        end
    end
  
    def edit
        @site = Site.find(params[:id])
        if !@site.can_edit?(current_user)
            #error_page("只有场所创建者或者高级用户才可以进行此操作。")
            raise ActiveRecord::RecordNotFound
        else
            @page_title = @site.title + ' - 编辑场所资料'
        end
        @site_categories = SiteCategory.find(:all).map{|u| [u.title, u.id]}
    end
  
    def update
        @site = Site.find(params[:id])
        @site.update_attributes(params[:site])
        flash[:notice] = '更新设施成功.'
        current_user.add_scores(2)
        redirect_to edit_site_url(@site)
    end
  
    def update_icon
        @site = Site.find(:first, :conditions => [ "id = ?", params[:id]])
        if !@site.can_edit?(current_user)
            #error_page("只有场所创建者或者高级用户才可以进行此操作。")
            raise ActiveRecord::RecordNotFound
        else
            @page_title = @site.title + ' - 修改场所图标'
        end
        return unless request.post?
        @site.disable_ferret
        @site.update_attributes(params[:site])
        current_user.add_scores(2)
        flash[:notice] = '更新设施成功.'
        redirect_to edit_site_url(@site)
    end
  
    def newpost
        @site = Site.find(params[:id])
        @post = SitePost.new(params[:post])
        @page_title = ' - 发表新贴'
        @user_tags = user_tags(current_user.id)
        @all_users_tags = user_tags
        return unless request.post?
        if params[:post]
            @post.replied_at = Time.now.utc
            @post.save!
            @post.tag_with(params[:newpost][:tags])
            
            Tag.parse(params[:newpost][:tags]).each do |name|
                exist_tags = Tag.find_by_sql ["SELECT * FROM tags INNER JOIN user_tags ON tags.id = user_tags.tag_id WHERE tags.name = ? AND user_tags.user_id = ?", name, current_user.id]
                if exist_tags.empty?
                    tag = Tag.find(:first, :conditions => [ "name = ?", name])
                    #current_user.tags.push(tag)
                    user_tag = UserTag.new(:user => current_user, :tag => tag)
                    user_tag.save!
                end
            end
	  
            current_user.posts << @post
            current_user.add_scores(2)
            redirect_post_url(@post)
        end
        rescue ActiveRecord::RecordInvalid
        render :action => 'newpost', :id => @site
    end
  
    def set_neighbor
        @site = Site.find(:first, :conditions => [ "id = ?", params[:id]])
        if !@site.nil? && !current_user.is_live_in(@site.communities)
            Site.transaction do
                #@site.communities.push_with_attributes(current_user.community)
                community_site = CommunitySite.new(:community => current_user.community, :site => @site)
                community_site.save!
                current_user.add_scores(2)
            end
        end
        #set session
        if session[:site_set_neighbor].nil?
            session[:site_set_neighbor] = Array.new
        end
        session[:site_set_neighbor].push(@site.id)
        render :text => "谢谢参与"
    end
  
    def votegood
        @site = Site.find(params[:id])
        Site.transaction do
            @site.votegood_count = @site.votegood_count + 1
            @site.save!
        end
        #set session
        if session[:site_vote].nil?
            session[:site_vote] = Array.new
        end
        session[:site_vote].push(@site.id)
        
        render :text => "#{@site.votegood_count}/#{@site.votegood_count + @site.votebad_count}的人觉得好，你的投票已经提交，谢谢。"
    end
  
    def votebad
        @site = Site.find(params[:id])
        Site.transaction do
            @site.votebad_count = @site.votebad_count + 1
            @site.save!
        end
        #set session
        if session[:site_vote].nil?
            session[:site_vote] = Array.new
        end
        session[:site_vote].push(@site.id)
        
        render :text => "#{@site.votegood_count}/#{@site.votegood_count + @site.votebad_count}的人觉得好，你的投票已经提交，谢谢。"
    end
  
    private
    def site_tags(id)
        tags = Tag.tags(:limit => 100, :order => "updated_at desc", :type => "site", :which => id)
    end
end
